import random

formulaNum = 30
operator = "+-×÷"


def genArithmetic(maxValue, op, withResult=False):
    retString = ''
    result = 0
    num1 = random.randint(0, maxValue)  # 随机生成第一个整数
    num2 = random.randint(0, maxValue)  # 随机生成第二个整数
    if op == '+':
        result = num1 + num2

    elif op == '×':
       	result = num1 * num2

    elif op == '-' and (num1 >= num2):
    	result = num1 - num2

    elif op == '-' and (num1 < num2):
        num1, num2 = num2, num1
        result = num1 - num2

    elif op == '÷' and (num1 != 0):
     	num2 = random.randint(1, maxValue // num1)
     	multiResult = num1 * num2
     	result = num1
     	num1 = multiResult
    elif op == '÷' and (num1 == 0):
    	result = 0
    else:
    	result = '运算符错误'

    # 利用字符串格式化生成算式字符串
    if withResult:
        retString = "{0}{1}{2} = {3}".format(num1, op, num2, result)
    else:
        retString = "{0}{1}{2} = ".format(num1, op, num2)
    return retString


with open('formula.txt', 'w') as myFile:
    for i in range(formulaNum):
        ariString = genArithmetic(100, random.choice(operator), 1)
        myFile.write("{:<30}".format(ariString))
        if (i+1) % 3 == 0:
            myFile.write("\n")

print('生成四则算式完成！')
